import React, {Component} from 'react';
import {Grid,Dialog, Button,Input,Radio,Upload,Icon,Feedback,Select} from '@icedesign/base';
import {
  FormBinderWrapper as IceFormBinderWrapper,
  FormBinder as IceFormBinder,
  FormError as IceFormError,
} from '@icedesign/form-binder';
import './AddUser.scss';
import API from '../../../../../../../tools/API';

const {Row, Col} = Grid;
const { Group: RadioGroup } = Radio;
const { CropUpload } = Upload;
const { Combobox } = Select;
/**
*  添加用户
*/
export default class AddUser extends Component{
  constructor(props) {
     super(props);
     this.state = {
        visible: false,
        user:{
          sex:0,
          head_img:"http://file.homeins.cn/Fke0qbx9Jsy3oSgrCTn4FiDLWPRf"
        },
        dataSource :this.props.roleSelectData
     };
     this.onSuccess = this.onSuccess.bind(this);
  }

  onOpen = () => {
    this.setState({
      visible: true
    });
  };

  onClose = () => {
    this.setState({
      visible: false,
      user:{
        sex:0,
        head_img:"http://file.homeins.cn/Fke0qbx9Jsy3oSgrCTn4FiDLWPRf"
      }
    })
  };

  onOk = ()=>{
    this.refs.form.validateAll((errors, values) => {
      if(errors == null){
        API.saveUser(values.user).then((res) => {
          Feedback.toast.success("用户添加成功");
          //清空数据
          this.setState({
            visible: false,
            user:{
              sex:0,
              head_img:"http://file.homeins.cn/Fke0qbx9Jsy3oSgrCTn4FiDLWPRf"
            }
          });
          //刷新列表
          this.props.getUserList();
        })
      }
    });
  }

  beforeCrop(file) {
    // 返回 `false` 的方式
    if (file.size > 1024 * 1024 * 3) {
      Dialog.alert({
        content: "图片尺寸超过最大限制 3MB，请重新选择！",
        closable: false,
        title: "裁剪提醒"
      });
      return false;
    }

    // 返回 `promise` 的方式
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => {
        const img = new Image();
        img.onload = () => {
          if (img.width <= 1200) {
            resolve();
          } else {
            Dialog.alert({
              content: `图片宽度为${
                img.width
              }px, 超过最大限制 1200px，请重新选择！`,
              closable: false,
              title: "裁剪提醒"
            });
            reject(); // resolve(false) 也能阻断流程
          }
        };
        img.src = reader.result;
      };
      reader.readAsDataURL(file);
    });
  }

  onSuccess(res, dataUrl) {
    this.refs.targetViewer.src = dataUrl;
    this.state.user.head_img = dataUrl;
    this.setState(this.state);
  }

  render(){
    return(
      <div className="add-user-main">
        <Button onClick={this.onOpen} type="primary"> + 添加用户 </Button>
        <Dialog
          visible={this.state.visible}
          onOk={this.onOk}
          onCancel={this.onClose}
          onClose={this.onClose}
          title="新增用户"
          className="add-user-dialog"
        >
          <IceFormBinderWrapper
            value={this.state}
            ref="form">
              <Row justify='center' wrap={true} >
                <Col span='24' style={{textAlign:'center'}}>
                  <CropUpload
                    action="https://www.easy-mock.com/mock/5b960dce7db69152d06475bc/ice/upload" // https://www.easy-mock.com/mock/5b960dce7db69152d06475bc/ice/upload 该接口仅作测试使用，业务请勿使用
                    preview
                    previewList={[80, 60, 40]}
                    minCropBoxSize={100}
                    beforeCrop={this.beforeCrop}
                    onSuccess={this.onSuccess}
                  >
                  {/* CropUpload 内嵌的标签会成为呼出系统弹窗的 trigger */}
                  <div >
                    <img
                      ref="targetViewer"
                      src={this.state.user.head_img}
                      width="80px"
                      height="80px"
                      style={{
                        borderRadius:80
                      }}
                    />
                  </div>
                  {/* trigger end */}
                </CropUpload>
                </Col>
                <Col span="24">
                  <Row justify='center'>
                    <Col s='9' xxs='6' className="add-user-label">姓名：</Col>
                    <Col s='15' xxs='18'>
                      <IceFormBinder  triggerType="onBlur" max={10}>
                        <Input size="large" placeholder="管理员" name="user.nick_name" />
                      </IceFormBinder>
                      <div><IceFormError className="err" name="user.nick_name" /></div>
                    </Col>
                  </Row>
                </Col>
                <Col span="24">
                  <Row justify='center'>
                    <Col s='9' xxs='6' className="add-user-label">登录名：</Col>
                    <Col s='15' xxs='18'>
                      <IceFormBinder rules={[
                          {
                            type: 'string',
                            required: true,
                            message: '必填',
                          },{
                            type: 'string',
                            max:10,
                            message: '不能超过10个字符',
                          },{
                            validator(
                              rule,
                              value,
                              callback,
                              source,
                              options
                            ) {
                              var errors = [];
                              var res = API.verifyUserName({user_name:value});
                              if (!res.result.flag) {
                                errors.push('用户名重复');
                              }
                              callback(errors);
                            },
                          }
                        ]} triggerType="onBlur" >
                        <Input size="large" placeholder="admin" name="user.user_name"/>
                      </IceFormBinder>
                      <div><IceFormError className="err" name="user.user_name" /></div>
                    </Col>
                  </Row>
                </Col>
                <Col span="24">
                  <Row justify='center'>
                    <Col s='9' xxs='6' className="add-user-label">昵称：</Col>
                    <Col s='15' xxs='18'>
                      <IceFormBinder  name="user.sex" >
                        <RadioGroup style={{marginTop:8}}>
                            <Radio value={1}>男</Radio>
                            <Radio value={2}>女</Radio>
                            <Radio value={0}>其他</Radio>
                         </RadioGroup>
                      </IceFormBinder>
                      <div><IceFormError className="err" name="user.sex" /></div>
                    </Col>
                  </Row>
                </Col>
                <Col span="24">
                  <Row justify='center'>
                    <Col s='9' xxs='6' className="add-user-label">角色：</Col>
                    <Col s='15' xxs='18'>
                      <IceFormBinder  name="user.role" >
                        <Combobox
                          filterLocal={false}
                          value={""}
                          fillProps="label"
                          multiple={true}
                          size="medium"
                          placeholder="选择角色"
                          dataSource={this.state.dataSource}
                          style={{width:200}}/>
                      </IceFormBinder>
                      <div><IceFormError className="err" name="user.role" /></div>
                    </Col>
                  </Row>
                </Col>
                <Col span="24">
                  <Row justify='center'>
                    <Col s='9' xxs='6' className="add-user-label">邮箱：</Col>
                    <Col s='15' xxs='18'>
                      <IceFormBinder required={true} type="email" triggerType="onBlur" message="请输入正确的邮件" >
                        <Input className="base-user-length" size="large" placeholder="***@***.com" name="user.email" />
                      </IceFormBinder>
                      <div><IceFormError className="err" name="user.email" /></div>
                    </Col>
                  </Row>
                </Col>
                <Col span="24">
                  <Row justify='center'>
                    <Col s='9' xxs='6' className="add-user-label">手机号：</Col>
                    <Col s='15' xxs='18'>
                      <IceFormBinder pattern={/^1(3|4|5|7|8)\d{9}$/} message='请输正确的手机号' triggerType="onBlur">
                        <Input className="base-user-length" size="large" placeholder="138********" name="user.phone" />
                      </IceFormBinder>
                      <div><IceFormError className="err" name="user.phone" /></div>
                    </Col>
                  </Row>
                </Col>
              </Row>
          </IceFormBinderWrapper>
        </Dialog>
      </div>
    )
  }

}
